package com.logistics.common.utils;


import com.alibaba.fastjson.JSON;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import static jdk.internal.dynalink.support.NameCodec.encode;

/**
 * 获得温
 *
 * @author 水穷处云起时
 * @date 2022/05/28
 */
public class HttpUtils {

    // java
// author: 金
// HttpUtils.java
    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url 例如：http://localhost:8080/demo
     * @return result
     */
    public static String sendGet(String url) throws Exception {
        URL realUrl = createURL(url, new HashMap<String, Object>(0));
        HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.connect();
        StringBuilder result = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }
        return result.toString();
    }

    /**
     * 拼接url路径返回一个完整的url
     *
     * @param url   路径： 发送请求的URL 例如：http://localhost:8080/login
     * @param param 参数： 请求参数 例：{ "userName":"admin", "password":"123456" }
     * @return
     * @throws MalformedURLException
     */
    private static URL createURL(String url, Map<String, Object> param) throws MalformedURLException {
        if (param == null || param.size() == 0) {
            return new URL(url);
        }
        StringBuilder sb = new StringBuilder(url);
        sb.append("?");
        for (String key : param.keySet()) {
            sb.append(key);
            sb.append("=");
            sb.append(encode(String.valueOf(param.get(key))));
            sb.append("&");
        }
        return new URL(sb.substring(0, sb.length() - 1));
    }

    // 调用文件
    public static String getOneS() throws Exception {
        try {
            /*创建地址 https://du.shadiao.app/api.php*/
            String result = HttpUtils.sendGet("https://api.shadiao.app/chp");
            Map<?, ?> map = JSON.parseObject(result, Map.class);
            String text = (String) ((Map<?, ?>) map.get("data")).get("text");
            return text;
        } catch (IOException e) {
            throw new RuntimeException("网站获取句子失败");
        }
    }
}
